package com.example.springsecurity.demo.handle;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationSuccessHandle implements AuthenticationSuccessHandler {

    private final String url;

    public MyAuthenticationSuccessHandle(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        User user = (User)authentication.getPrincipal();  //可以获取到user对象
        System.out.println(user.toString());  //其中密码因为安全的原因会打印None

        response.sendRedirect(url);  //重要的是这句, 重定向跳转
    }
}